package org.yxing.palpalgps.provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.provider.BaseColumns;

public class RecentChatsProvider extends ContentProvider {
    
    private static final String AUTHORITY = "org.yxing.palpalgps.provider.RecentChatsProvider";
    private static final String COTNENT = "recentchats";
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + COTNENT);
    public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.palpalgps.recentchat";
    public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.palpalgps.recentchat";
    private static final int RECENT_CHATS = 1;
    private static final int RECENT_CHAT_ID = 2;
    private static final int DB_VERSION = 2;
    private static final String DB_NAME = "recent_chat.db";
    private static final String TABLE_NAME = "recent_chats";
    private static final UriMatcher sUriMatcher;
    
    static {
        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(AUTHORITY, COTNENT, RECENT_CHATS);
        sUriMatcher.addURI(AUTHORITY, COTNENT + "/#", RECENT_CHAT_ID);
    }
    
    private DatabaseHelper mDatabaseHelper;
    
    public static interface RecentChats extends BaseColumns {
        public static final String UID = "uid";
        public static final String FUID = "fuid";
        public static final String NAME = "name";
        public static final String PORTRAIT = "portrait";
        public static final String LAST_MSG = "last_msg";
        public static final String LAST_TIMESTAMP = "last_timestamp";
        public static final String QUANTITY = "quantity";
        public static final String TYPE = "type";
        public static final String TYPE_CHAT = "chat";
        public static final String TYPT_GROUP = "group";
        
    }
    
    private static class DatabaseHelper extends SQLiteOpenHelper {

        public DatabaseHelper(Context context) {
            super(context, DB_NAME, null, DB_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            
            String sql = "CREATE TABLE " + TABLE_NAME + "("
                    + RecentChats._ID + " INTEGER PRIMARY KEY,"
                    + RecentChats.UID + " VARCHAR(64) NOT NULL,"
                    + RecentChats.FUID + " VARCHAR(64) NOT NULL,"
                    + RecentChats.NAME + " VARCHAR(128),"
                    + RecentChats.PORTRAIT + " VARCHAR(16),"
                    + RecentChats.TYPE + " VARCHAR(10),"
                    + RecentChats.LAST_MSG + " TEXT,"
                    + RecentChats.LAST_TIMESTAMP + " BIGINT,"
                    + RecentChats.QUANTITY + " INT DEFAULT(0))";
            db.execSQL(sql);
            
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
            onCreate(db);
        }
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        int count = db.delete(TABLE_NAME, selection, selectionArgs);
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public String getType(Uri uri) {
        String type = null;
        switch(sUriMatcher.match(uri)) {
        case RECENT_CHATS:
            type = CONTENT_TYPE;
            break;
        case RECENT_CHAT_ID:
            type = CONTENT_ITEM_TYPE;
            break;
        default:
            throw new IllegalArgumentException("Unkonw URI " + uri);
        }
        return type;
    }

    public Uri insert(Uri uri, ContentValues values) {
        if (!values.containsKey(RecentChats.LAST_TIMESTAMP))
            values.put(RecentChats.LAST_TIMESTAMP, System.currentTimeMillis());
        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        long id = db.insert(TABLE_NAME, RecentChats._ID, values);
        if (id > 0) {
            Uri rowUid = ContentUris.withAppendedId(CONTENT_URI, id);
            getContext().getContentResolver().notifyChange(rowUid, null);
            return rowUid;
        }
        throw new SQLException("Failed to insert row into " + uri);
    }

    /**
     * on create
     */
    public boolean onCreate() {
        mDatabaseHelper = new DatabaseHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) {
        SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
        Cursor c = db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
        c.setNotificationUri(getContext().getContentResolver(), uri);
        return c;
    }

    @Override
    public int update(Uri uri, ContentValues values, String whereClause, String[] whereArgs) {
        if (!values.containsKey(RecentChats.LAST_TIMESTAMP))
            values.put(RecentChats.LAST_TIMESTAMP, System.currentTimeMillis());
        SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
        int count = db.update(TABLE_NAME, values, whereClause, whereArgs);
        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

}
